package com.bear.sgg.springboot_06_web.controller;

import com.bear.sgg.springboot_06_web.dao.DepartmentDao;
import com.bear.sgg.springboot_06_web.dao.EmployeeDao;
import com.bear.sgg.springboot_06_web.entity.Department;
import com.bear.sgg.springboot_06_web.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.Collection;
import java.util.Map;

/**
 * @ClassNmae EmpController
 * @Description 员工信息控制器
 * @Author bear
 * @Date 2020/3/10 0010 上午 10:54
 */
@Controller
public class EmpController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

   /**
     * 查询所有员工信息并跳转到员工页面
     * @param map
     * @return
     */
    @GetMapping("/emps")
    public String toShowAllEmpPage(Map<String, Object> map) {
        Collection<Employee> emps = employeeDao.getAll();
        //System.out.println("查询结果为：" + emps);
        map.put("emps", emps);
        return "emp/list";
    }

    /**
     * 跳转到添加emp信息页面
     * @return
     */
    @GetMapping("/emp")
    public String toAddEmpPage(Model model) {
        Collection<Department> deps = departmentDao.getDepartments();
        model.addAttribute("deps", deps);
        return "emp/add";
    }

    /**
     * 添加员工信息
     * @param employee
     * @return
     */
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        //System.out.println("添加的员工信息为：" + employee);
        employeeDao.save(employee);
        //重定向到员工列表
        return "redirect:/emps";
    }

    /**
     * 跳转到修改员工信息页面
     *
     * @param id
     * @return
     */
    @GetMapping("/emp/{id}")
    public String toUpdatePage(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("emp", employeeDao.get(id));
        model.addAttribute("deps", departmentDao.getDepartments());
        return "emp/update";
    }

    /**
     * 更新员工信息
     * @param employee
     * @return
     */
    @PutMapping("/emp")
    public String updateEmp(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}

